/**
 * 
 */
package com.gmail.avereshchaga.db.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gmail.avereshchaga.db.entity.EmployeeImpl;
import com.gmail.avereshchaga.db.entity.IEmployee;

/**
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 * 
 */

@Repository
public class EmployeeDAOImpl implements IEmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void createEmployee(IEmployee employee) {
        sessionFactory.getCurrentSession().save(employee);
    }

    public IEmployee readEmployee(Long id) {
        return (IEmployee) sessionFactory.getCurrentSession().get(
                "com.gmail.avereshchaga.db.entity.EmployeeImpl", id);
    }

    public void updateEmployee(IEmployee employee) {
        sessionFactory.getCurrentSession().update(employee);
    }

    public List<IEmployee> findAll(String param, Integer page) {
        Session sess = sessionFactory.getCurrentSession();
        Criteria crit = sess.createCriteria(EmployeeImpl.class);
        crit.addOrder(Order.asc("lastName")).
        add(Restrictions.or(
                Restrictions.ilike("lastName", param),
                Restrictions.ilike("firstName", param))).
        setFirstResult(page * 20).
        setMaxResults(20);
        List<IEmployee> employees = crit.list();
        return employees;
    }
    
    public Integer definitionQuantityOfEntities(String param){
        Session sess = sessionFactory.getCurrentSession();
        Criteria crit = sess.createCriteria(EmployeeImpl.class);
        crit.add(Restrictions.or(
                Restrictions.ilike("lastName", param),
                Restrictions.ilike("firstName", param)))
        .setProjection(Projections.rowCount());
        Integer quantityOfEntities = (Integer) crit.uniqueResult();
        return quantityOfEntities;
    }

    /**
     * @return the sessionFactory
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * @param sessionFactory
     *            the sessionFactory to set
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
